<?php

namespace app\admin\controller;

use think\Config;

class Upload extends Base
{
    public function file_images() {
        $ret = array();
        //返回的上传文件状态数组
        if ($_FILES["file"]["error"] > 0) {
            $ret["message"] = $_FILES["file"]["error"];
            $ret["status"] = 0;
            $ret["src"] = "";
            return json($ret);
        } else {
            $pic = $this->upload();
            if ($pic['info'] == 1) {
                $url ='/uploads' .DS. $pic['savename'];
                $url = str_replace("\\","/",$url);
            } else {
                $ret["message"] = $this->error($pic['err']);
                $ret["status"] = 0;
            }
            $ret = [
                'code'=>200,
                'msg'=>'',
                'data'=>['src'=>$url],
            ];
            return json($ret);
        }
    }


    //图片上传代码
    private function upload() {
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        $reubfo = array(); //定义一个返回的数组
        if ($info) {
            $reubfo['info'] = 1;
            $reubfo['savename'] = $info->getSaveName();
        } else { // 上传失败获取错误信息
            $reubfo['info'] = 0;
            $reubfo['err'] = $file->getError();;
        }
        return $reubfo;
    }

    /**
     * 富文本编辑器内容图片上传
     * @return mixed
     */
    public function editUpload()
    {
        if($this->request->isPost()){
            $res['code'] = 0;
            $res['msg'] = '上传成功!';
            //获取表单上传文件
            $file = $this->request->file('file');
            //移动到框架public/uploads/目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $res['data']['title'] = $info->getFilename();
                $url = '/uploads' .DS. $info->getSaveName();
                $url = str_replace("\\","/",$url);
                $res['data']['src'] = $url;
            }else{
                $res['code'] = 1;
                $res['msg'] = '上传失败!'.$file->getError();
            }
            return $res;
        }
    }

}